package com.jweb.framework.http.support;

import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.util.CookieGenerator;
import org.springframework.web.util.WebUtils;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明 ： 本地资源解析
 */
public class SmartLocaleResolver extends CookieGenerator implements LocaleResolver{
	
	public static final String LOCALE_ATTRIBUTE_NAME = SmartLocaleResolver.class.getName() + ".LOCALE" ;
	public static final String DEFAULT_COOKIE_NAME = SmartLocaleResolver.class.getName() + ".LOCALE" ;
	private Locale defaultLocale ;
	private boolean useCookie ;
	
	public SmartLocaleResolver(){
		setCookieName(DEFAULT_COOKIE_NAME);
		setCookieMaxAge(Integer.valueOf(2592000));
	}
	
	public void setDefaultLocale(Locale defaultLocale) {
		this.defaultLocale = defaultLocale;
	}

	public void setUseCookie(boolean useCookie) {
		this.useCookie = useCookie;
	}
	

	public Locale resolveLocale(HttpServletRequest request) {
		
		Locale locale = (Locale) request.getAttribute(LOCALE_ATTRIBUTE_NAME); // "locale"=null
		if(locale!=null){
			return locale ;
		}
		
		locale = (Locale) WebUtils.getSessionAttribute(request, LOCALE_ATTRIBUTE_NAME); // locale=null
		if(locale==null && this.useCookie){ //false
			Cookie cookie = WebUtils.getCookie(request, getCookieName());
			if(cookie!=null){
				locale = StringUtils.parseLocaleString(cookie.getValue());
			}
		}
		
		if(locale==null){
			locale = determimeDefaultLocale(request); // "locale"=Locale
		}
		
		if(locale!=null){
			request.setAttribute(LOCALE_ATTRIBUTE_NAME, locale);
		}
		
		return locale ;
	}

	
	private Locale determimeDefaultLocale(HttpServletRequest request) {
		
		Locale locale = this.defaultLocale ;
		if(locale == null){
			locale = request.getLocale() ;
		}
		
		return locale ;
	}

	public void setLocale(HttpServletRequest request,HttpServletResponse response, Locale locale) {
		
		if(locale!=null){
			setSession(request , LOCALE_ATTRIBUTE_NAME , locale);
			if(this.useCookie){
				addCookie(response, locale.toString());
			}
		}
		else{
			setSession(request, LOCALE_ATTRIBUTE_NAME, null);
			if(this.useCookie){
				removeCookie(response);
			}
		}
		
	}

	private void setSession(HttpServletRequest request,String localeAttributeName, Locale locale) {
		
		Assert.notNull(request , "Request must not be null ");
		HttpSession httpSession = request.getSession();
		if(httpSession!=null){
			if(locale!=null){
				httpSession.setAttribute(localeAttributeName, locale);
			}
			else{
				httpSession.removeAttribute(localeAttributeName);
			}
		}
		
	}

}
